package com.ly.controller;

import cn.hutool.core.io.FileUtil;
import cn.hutool.core.util.IdUtil;
import cn.hutool.core.util.StrUtil;
import com.ly.common.Result;
import com.ly.common.StatusEnum;
import com.ly.common.TokenHandler;
import com.ly.dao.UserDao;
import com.ly.dao.UserTokenDao;
import com.ly.entity.User;
import com.ly.rep.LoginRep;
import com.ly.req.LoginReq;
import com.ly.service.UserService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.io.IOException;

@RestController
@RequestMapping("/file")
@Api(tags = "文件上传模块")
public class FileController {
    @Value("${server.port}")
    private String port;
    private static final  String UPLOAD_PATH = System.getProperty("user.dir") + File.separator + "/files";

    @PostMapping("/upload")
    @ApiOperation(value = "文件上传")
    public Result<?> upload(@RequestParam MultipartFile file) throws IOException {
        //1.获取文件名 (111.jpg)
        String originalFilename = file.getOriginalFilename();
        //2.获取文件类型 (jpg)
        String fileType = FileUtil.extName(originalFilename);
        //3.定义一个文件的标识 (c208a3dea95d40e388050cde32a27393.jpg)
        String fileUUID = IdUtil.fastSimpleUUID() + StrUtil.DOT + fileType;
        //4.开始上传
        File uplodFile = new File(UPLOAD_PATH +"/"+ fileUUID);
        //6.如果file文件夹不存在,则创建一个
        File parentFile = uplodFile.getParentFile();
        if(!parentFile.exists()){
            parentFile.mkdir();
        }
        //7.上传文件到磁盘
        file.transferTo(uplodFile);
        //8.返回给前端
        String url = "http://localhost:" + port + "/file/" + fileUUID;
        return  new Result<>(url,StatusEnum.SUCCESS);
    }

}
